package com.wtzz.police.base.service.impl;

import com.wtzz.police.base.entity.User;
import com.wtzz.police.base.model.response.JwtAuthenticationResponse;
import com.wtzz.police.base.service.AuthService;
import com.wtzz.police.base.service.UserService;
import com.wtzz.police.base.util.component.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 类说明
 *
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    private AuthenticationManager authenticationManager;
    private UserService userService;
    private JwtTokenUtil jwtTokenUtil;

    public AuthServiceImpl(AuthenticationManager authenticationManager, UserService userService, JwtTokenUtil jwtTokenUtil) {
        super();
        this.authenticationManager = authenticationManager;
        this.userService = userService;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Override
    public JwtAuthenticationResponse login(String username, String password) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails = userService.loadUserByUsername(username);
        JwtAuthenticationResponse token = jwtTokenUtil.generateToken(userDetails);
        log.info("【{}】登录系统", ((User) userDetails).getFullname());
        return token;
    }

    @Override
    public JwtAuthenticationResponse refresh(String oldToken) {
        return jwtTokenUtil.refreshToken(oldToken);
    }

    @Override
    public Optional<User> getUserInfo(String token) {
        jwtTokenUtil.validateToken(token);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        return userService.findByUsername(username);
    }

}
